package com.sqx.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.dao.TbCouponDao;
import com.sqx.modules.coupon.entity.TbCoupon;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.dao.GoodsSkuDao;
import com.sqx.modules.goods.entity.*;
import com.sqx.modules.goods.service.*;
import com.sqx.modules.goods.utils.SkuUtil;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.shop.dao.ShopMessageDao;
import com.sqx.modules.sys.dao.SysUserRoleDao;
import com.sqx.modules.sys.entity.SysUserRoleEntity;
import com.sqx.modules.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {

    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsSkuDao goodsSkuDao;
    @Autowired
    private GoodsAttrService goodsAttrService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private GoodsAttrValueService goodsAttrValueService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private ShopMessageDao shopMessageDao;
    @Autowired
    private TbIndentService tbIndentService;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    @Autowired
    private TbCouponDao tbCouponDao;

    @Transactional
    @Override
    public Result insertGoods(Goods goods) {
        //判断商户保证金是否足够
        CommonInfo one = commonInfoService.findOne(270);
        GoodsShop goodsShop = shopMessageDao.selectOne(new QueryWrapper<GoodsShop>().eq("shop_id", goods.getShopId()));
        if (goodsShop.getCashDeposit().doubleValue() < Double.valueOf(one.getValue())) {
            return Result.error("您的保证金不足，请交保证金后再发布商品！");
        }
        //添加商品信息
        goods.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goods.setStatus(0);
        goods.setSalesVolume(0);
        goodsDao.insert(goods);

        GoodsShopRelevancy goodsShopRelevancy = new GoodsShopRelevancy();
        goodsShopRelevancy.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goodsShopRelevancy.setGoodsId(goods.getGoodsId());
        goodsShopRelevancy.setInventory(0);
        goodsShopRelevancy.setStatus(0);
        goodsShopRelevancy.setShopId(goods.getShopId());
        goodsShopRelevancy.setSales(0);
        goodsShopDao.addGoodsShopRelevancy(goodsShopRelevancy);

        //添加规格信息
        if (goods.getAttr().size() > 0) {
            List<GoodsAttr> attr = goods.getAttr();
            for (GoodsAttr a : attr) {
                a.setGoodsId(goods.getGoodsId());
                goodsAttrService.saveGoodsAttr(a);
            }
        }
        List<GoodsSku> sku = goods.getSku();
        if(sku==null || sku.size()==0){
            GoodsSku goodsSku=new GoodsSku();
            goodsSku.setSkuImg(goods.getGoodsCover());
            goodsSku.setSkuOriginalPrice(goods.getOriginalMoney());
            goodsSku.setSkuPrice(goods.getGoodsMoney());
            goodsSku.setGoodsId(goods.getGoodsId());
            goodsSkuService.save(goodsSku);
        }else{
            for (GoodsSku v : sku) {
                v.setGoodsId(goods.getGoodsId());
                goodsSkuService.save(v);
            }
        }
        return Result.success();


        /*//添加规格信息
        List<GoodsSku> goodsSkuList = goods.getGoodsSkuList();
        get(goodsSkuList, 0L, goods.getGoodsId());
        return Result.success();*/
    }

    /*public void get(List<GoodsSku> goodsSkuList, Long parentId, Long goodsId){
        for(int i = 0;i<goodsSkuList.size();i++){
            GoodsSku goodsSku = goodsSkuList.get(i);
            goodsSku.setParentId(parentId);
            goodsSku.setGoodsId(goodsSku.getGoodsId());
            goodsSku.setGoodsId(goodsId);
            goodsSkuDao.insertGoodsSku(goodsSku);
            if(goodsSku.getGoodsSkuList().size()>0){
                get(goodsSku.getGoodsSkuList(), goodsSku.getSkuId(), goodsId);
            }
        }
    }*/


    @Override
    public Result selectGoodsList(Long shopId, Double lng, Double lat) {
        GoodsShop goodsShop = goodsShopDao.selectGoodsList(shopId, lng, lat);
        //List<Goods> goodsList = goodsDao.selectGoodsClassifyList(shopId);
        List<GoodsClassify> goodsClassifies = goodsDao.selectAllClassifyList(null, shopId);
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < goodsClassifies.size(); i++) {
            Map<String, Object> hashMap = new HashMap<>();
            GoodsClassify goodsClassify = goodsClassifies.get(i);
            List<Goods> goodsList1 = goodsDao.selectGoodsByClassify(goodsClassify.getClassifyId(), shopId);
            hashMap.put("classifyId", goodsClassifies.get(i).getClassifyId());
            hashMap.put("classifyName", goodsClassify.getClassifyName());
            hashMap.put("goodsList", goodsList1);
            list.add(hashMap);
        }
        CommonInfo one = commonInfoService.findOne(292);
        CommonInfo one1 = commonInfoService.findOne(293);
        if (goodsShop.getDistance() == null) {
            goodsShop.setDistance(0.00);
        }
        BigDecimal a = BigDecimal.valueOf(goodsShop.getDistance()).divide(new BigDecimal(one.getValue()), 2, BigDecimal.ROUND_HALF_DOWN);
        if (a.doubleValue() < Double.parseDouble(one1.getValue())) {
            a = new BigDecimal(one1.getValue());
        }
        goodsShop.setErrandTime(a.doubleValue());
        Map<String, Object> result = new HashMap<>();
        result.put("goodsShop", goodsShop);
        result.put("list", list);
        return Result.success().put("data", result);
    }

    @Transactional
    @Override
    public Result updateGoods(Goods goods) {
        if (goods.getAttr() != null && goods.getAttr().size() > 0) {
            GoodsAttr attr = goods.getAttr().get(goods.getAttr().size() - 1);
            attr.setGoodsId(goods.getGoodsId());
            goodsAttrService.updateGoodsAttr(attr);
        } else { //修改为单规格，删除所有attr
            goodsAttrService.deleteAttrAndValue(goods.getGoodsId());
        }
        //2.修改所有sku
        goodsSkuService.deleteGoodsSkuByGoodsId(goods.getGoodsId());
        List<GoodsSku> sku = goods.getSku();

        if(sku==null || sku.size()==0){
            GoodsSku goodsSku=new GoodsSku();
            goodsSku.setSkuImg(goods.getGoodsCover());
            goodsSku.setSkuOriginalPrice(goods.getOriginalMoney());
            goodsSku.setSkuPrice(goods.getGoodsMoney());
            goodsSku.setGoodsId(goods.getGoodsId());
            goodsSkuService.save(goodsSku);
        }else{
            for (GoodsSku goodsSku : sku) {
                goodsSku.setGoodsId(goods.getGoodsId());
                goodsSkuService.save(goodsSku);
            }
        }
        goodsDao.updateById(goods);
        //修改库存和状态
        GoodsShopRelevancy goodsShopRelevancy = new GoodsShopRelevancy();
        goodsShopRelevancy.setInventory(goods.getInventory());
        goodsShopRelevancy.setStatus(goods.getStatus());
        QueryWrapper<GoodsShopRelevancy> wrapper = new QueryWrapper<>();
        wrapper.eq("shop_id", goods.getShopId()).eq("goods_id", goods.getGoodsId());
        goodsShopRelevancyDao.update(goodsShopRelevancy, wrapper);
        return Result.success();
    }

    @Transactional
    @Override
    public Result isFormatAttr(GoodsAttr goodsAttr, String coverImg, String originalPrice, String price) {
        //1.获取商品规格值
        List<GoodsAttrValue> attr = goodsAttr.getAttrValue();
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        //3.sku规格处理集合
        List<List<String>> skuInputList = new ArrayList<>();
        //4.循环规格值
        for (int i = 0; i < attrSize; i++) {
            //5.放入表头数据
            header.add(attr.get(i).getValue());
            //6.sku规格计算
            String detail = attr.get(i).getDetail();
            String[] split = detail.split(",");
            List<String> skuList = new ArrayList<>();
            for (int j = 0; j < split.length; j++) {
                skuList.add(split[j]);
            }
            skuInputList.add(skuList);
        }
        //8.sku规格种类
        List<List<String>> skuList = SkuUtil.skuSort(skuInputList); //计算规格种类
        for (int i = 0; i < skuList.size(); i++) {
            Map<String, Object> sku = new HashMap<>();
            List<String> strings = skuList.get(i);
            String[] arr = strings.toArray(new String[strings.size()]);
            String json = "";
            for (int j = 0; j < attrSize; j++) {
                String arrString = arr[j];
                sku.put("value" + j, arrString);
                json += arrString + ",";
            }
            json = json.substring(0, json.length() - 1);
            sku.put("json", json);
            sku.put("detailJson", json);
            sku.put("skuImg", coverImg);
            sku.put("skuOriginalPrice", originalPrice);
            sku.put("skuPrice", price);
            //    sku.put("stock", 999);
            //    sku.put("sales", 0);
            value.add(sku);
        }
        //表头
        header.add("图片");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPrice)) {
            header.add("原价");
        }
        header.add("售价");
        //  header.add("库存");
        //   header.add("销量");
        header.add("操作");
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data", map);
    }

    @Transactional
    @Override
    public Result onlyFormatAttr(String coverImg, String originalPrice, String price) {
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        //表头
        header.add("图片");
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(originalPrice)) {
            header.add("原价");
        }
        header.add("售价");
        //  header.add("库存");
        //  header.add("销量");
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        Map<String, Object> sku = new HashMap<>();
        sku.put("json", null);
        sku.put("detailJson", null);
        sku.put("skuImg", coverImg);
        sku.put("skuOriginalPrice", originalPrice);
        sku.put("skuPrice", price);
        //   sku.put("'%Y-%m-%d'", 999);
        //   sku.put("sales", 0);
        value.add(sku);
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data", map);
    }

    @Override
    public Result formatAttr(Long goodsId) {
        //1.获取商品规格值
        List<GoodsAttrValue> attr = goodsAttrValueService.findAllByGoodsId(goodsId);
        //sku集合
        List<GoodsSku> goodsSkuList = goodsSkuService.selectGoodsSkuByGoodsId(goodsId);
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        if (attrSize > 0) {
            //4.循环规格值
            for (int i = 0; i < attrSize; i++) {
                //5.放入表头数据
                header.add(attr.get(i).getValue());
            }
        }
        header.add("图片");
        header.add("原价");
        header.add("售价");
        //   header.add("库存");
        //   header.add("销量");
        header.add("操作");
        //5.sku数据放入
        for (GoodsSku s : goodsSkuList) {
            Map<String, Object> sku = new HashMap<>();
            String detailJson = s.getDetailJson();
            if (detailJson != null) {
                String[] split = detailJson.split(",");
                for (int i = 0; i < split.length; i++) {
                    sku.put("value" + i, split[i]);
                }
            }
            sku.put("detailJson", detailJson);
            sku.put("skuOriginalPrice", s.getSkuOriginalPrice());
            sku.put("skuPrice", s.getSkuPrice());
            //  sku.put("stock", s.getStock());
            //   sku.put("sales", s.getSales());
            sku.put("skuImg", s.getSkuImg());
            value.add(sku);
        }
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return Result.success().put("data", map);
    }

    @Override
    public Result findAttrValue(Long goodsId) {
        List<GoodsAttr> attrList = goodsAttrService.findAllByGoodsId(goodsId);
        GoodsAttr s = new GoodsAttr();
        if (attrList.size() > 0 && attrList != null) {
            s = attrList.get(0);
            s.setAttrValue(goodsAttrValueService.findAllByGoodsId(goodsId));
        }
        return Result.success().put("data", s);
    }

    @Override
    public Result selectShortShop(double lng, double lat, String shopName, Integer page, Integer limit, Long shopId) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        IPage<GoodsShop> goodsShopIPage = goodsDao.selectShortShop(pages, lng, lat, shopName, shopId);
        CommonInfo one = commonInfoService.findOne(235);
        for (int i = 0; i < goodsShopIPage.getRecords().size(); i++) {

            String way = commonInfoService.findOne(416).getValue();
            if ("1".equals(way)) {
                String url = "https://apis.map.qq.com/ws/geocoder/v1/";
                Map<String, String> maps = new HashMap<>();
                maps.put("location", goodsShopIPage.getRecords().get(i).getShopLat() + "," + goodsShopIPage.getRecords().get(i).getShopLng());
                maps.put("key", one.getValue());
                String data = HttpClientUtil.doGet(url, maps);
                JSONObject jsonObject = JSON.parseObject(data);
                String status = jsonObject.getString("status");
                if ("0".equals(status)) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONObject adInfo = result.getJSONObject("ad_info");
                    String province = adInfo.get("province").toString();
                    String city = adInfo.get("city").toString();
                    String district = adInfo.get("district").toString();
                    goodsShopIPage.getRecords().get(i).setProvince(province);
                    goodsShopIPage.getRecords().get(i).setCity(city);
                    goodsShopIPage.getRecords().get(i).setDistrict(district);
                } else {
                    log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                }
            } else {
                String value = commonInfoService.findOne(417).getValue();
                String url = "http://api.tianditu.gov.cn/geocoder";
                Map<String, String> param = new HashMap<>();
                JSONObject postStr = new JSONObject();
                postStr.put("lon", goodsShopIPage.getRecords().get(i).getShopLng());
                postStr.put("lat", goodsShopIPage.getRecords().get(i).getShopLat());
                postStr.put("ver", "1");
                param.put("postStr", postStr.toJSONString());
                param.put("type", "geocode");
                param.put("tk", value);
                String s = HttpClientUtil.doGet(url, param);
                JSONObject jsonObject = JSONObject.parseObject(s);
                String status = jsonObject.getString("status");
                if ("0".equals(status)) {
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONObject addressComponent = result.getJSONObject("addressComponent");
                    String province = addressComponent.getString("province");
                    String city = addressComponent.getString("city");
                    String county = addressComponent.getString("county");
                    goodsShopIPage.getRecords().get(i).setProvince(province);
                    goodsShopIPage.getRecords().get(i).setCity(city);
                    goodsShopIPage.getRecords().get(i).setDistrict(county);
                }
            }

        }
        PageUtils pageUtils = new PageUtils(goodsShopIPage);
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAllShop(Integer page, Integer limit, String shopName, String region, Integer isActivity) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectAllShop(pages, shopName, region, isActivity));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAdminGoodsList(Integer page, Integer limit, Integer classifyId, String goodsName, Integer status, Long shopId, String shopName) {
        Page<Goods> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectAdminGoodsList(pages, classifyId, goodsName, status, shopId, shopName));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result selectAllClassify(Integer page, Integer limit, String shopName, Long shopId) {
        if (page == null || limit == null) {
            List<GoodsClassify> goodsClassifies = goodsDao.selectAllClassifyList(shopName, shopId);
            return Result.success().put("data", goodsClassifies);
        } else {
            Page<GoodsClassify> pages = new Page<>(page, limit);
            IPage<GoodsClassify> goodsClassifies = goodsDao.selectAllClassify(pages, shopName, shopId);
            return Result.success().put("data", goodsClassifies);
        }
    }

    @Override
    public Result shopAddGoods(Long shopId, List goodsIdList) {
        goodsDao.shopAddGoods(shopId, goodsIdList);
        return Result.success();
    }

    @Override
    public Result deleteGoodsById(Long goodsId) {
        goodsDao.delete(new QueryWrapper<Goods>().eq("goods_id", goodsId));
        goodsAttrService.deleteGoodsAttr(goodsId);
        return Result.success();
    }

    @Override
    public Result selectAllShopList(Long userId) {
        List<SysUserRoleEntity> sysUserRoleEntityList = sysUserRoleDao.selectList(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));
        List list = new ArrayList();
        for (int a = 0; a < sysUserRoleEntityList.size(); a++) {
            list.add(sysUserRoleEntityList.get(a).getRoleId());
        }
        if (list.size() == 1 && list.contains(12L)) {
            List<GoodsShop> goodsShops = goodsShopDao.selectListByAdmin(userId);
            return Result.success().put("data", goodsShops);
        } else {
            List<GoodsShop> goodsShops = goodsShopDao.selectList(null);
            return Result.success().put("data", goodsShops);
        }
    }

    @Override
    public Result selectShop(Integer page, Integer limit, Integer screen, Integer shopTypeId, Double lng, Double lat, String impotr, Long activityId) {
        //如果没有经纬度，则默认为北京的经纬度
        if (lng == null || lat == null || lng == 0 || lat == 0) {
//            lng = 108.8927;
//            lat = 34.2408;
            lng = 121.47;
            lat = 31.23;
        }
        Page<GoodsShop> pages = new Page<>(page, limit);
        String way = commonInfoService.findOne(416).getValue();
        String city;
        if ("1".equals(way)) {
            CommonInfo one = commonInfoService.findOne(235);
            String url = "https://apis.map.qq.com/ws/geocoder/v1/";
            Map<String, String> maps = new HashMap<>();
            maps.put("location", lat + "," + lng);
            maps.put("key", one.getValue());
            String data = HttpClientUtil.doGet(url, maps);
            JSONObject jsonObject = JSON.parseObject(data);
            String status = jsonObject.getString("status");
            if ("0".equals(status)) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                city = adInfo.getString("city");
            } else {
                log.error("转换失败！！！原因:" + jsonObject.getString("message"));
                return Result.error("获取定位失败！");
            }
        } else {
            String value = commonInfoService.findOne(417).getValue();
            String url = "http://api.tianditu.gov.cn/geocoder";
            Map<String, String> param = new HashMap<>();
            JSONObject postStr = new JSONObject();
            postStr.put("lon", lng);
            postStr.put("lat", lat);
            postStr.put("ver", "1");
            param.put("postStr", postStr.toJSONString());
            param.put("type", "geocode");
            param.put("tk", value);
            String s = HttpClientUtil.doGet(url, param);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String status = jsonObject.getString("status");
            if ("0".equals(status)) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject addressComponent = result.getJSONObject("addressComponent");
                city = addressComponent.getString("city");
            } else {
                return Result.error("获取定位失败！");
            }
        }

        IPage<GoodsShop> goodsShopIPage = goodsShopDao.selectShop(pages, screen, shopTypeId, lng, lat, city, impotr, activityId);
        List<GoodsShop> records = goodsShopIPage.getRecords();
        // 外卖商家计算配送时间系数
        //外卖商家最小配送时间（分钟）
        CommonInfo one1 = commonInfoService.findOne(292);
        CommonInfo one2 = commonInfoService.findOne(293);
        //改为使用stream拼接shopid 查询数据 后循环封装
        List<Long> shopIdList = records.stream().map(GoodsShop::getShopId).collect(Collectors.toList());

        List<Goods> goodsList = goodsDao.selectGoodsBySalesAndGoodsNameAndShopIds(shopIdList, impotr);
        Map<Long, List<Goods>> goodsMap = goodsList.stream().collect(Collectors.groupingBy(Goods::getShopId));

        List<TbCoupon> tbCoupons = tbCouponDao.selectCouponListByShopIdList(shopIdList, null);
        Map<Long, List<TbCoupon>> couponMap = tbCoupons.stream().collect(Collectors.groupingBy(TbCoupon::getShopId));

        for (int a = 0; a < goodsShopIPage.getRecords().size(); a++) {
            Long shopId = goodsShopIPage.getRecords().get(a).getShopId();
            goodsShopIPage.getRecords().get(a).setCouponList(couponMap.get(shopId));
            if (StringUtils.isNotEmpty(impotr)) {
                goodsShopIPage.getRecords().get(a).setGoodsList(goodsMap.get(shopId));
            } else {
                goodsShopIPage.getRecords().get(a).setGoodsList(new ArrayList<>());
            }
            Double distance = goodsShopIPage.getRecords().get(a).getDistance();
            double errandTime = distance / Double.parseDouble(one1.getValue());
            if (errandTime < Double.parseDouble(one2.getValue())) {
                errandTime = Double.parseDouble(one2.getValue());
            }
            goodsShopIPage.getRecords().get(a).setErrandTime(errandTime);
        }
        PageUtils pageUtils = new PageUtils(goodsShopIPage);
        return Result.success().put("data", pageUtils);

    }


    @Override
    public Result selectSearch(Integer page, Integer limit, String impotr, Double lng, Double lat) {
        Page<GoodsShop> pages = new Page<>(page, limit);
        String way = commonInfoService.findOne(416).getValue();
        if("1".equals(way)){
            CommonInfo one = commonInfoService.findOne(235);
            String url = "https://apis.map.qq.com/ws/geocoder/v1/";
            Map<String, String> maps = new HashMap<>();
            maps.put("location", lat + "," + lng);
            maps.put("key", one.getValue());
            String data = HttpClientUtil.doGet(url, maps);
            JSONObject jsonObject = JSON.parseObject(data);
            String status = jsonObject.getString("status");
            if ("0".equals(status)) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject adInfo = result.getJSONObject("ad_info");
                Object city = adInfo.get("city");
                PageUtils pageUtils = new PageUtils(goodsShopDao.selectSearch(pages, impotr, lng, lat, String.valueOf(city)));
                return Result.success().put("data", pageUtils);
            } else {
                log.error("转换失败！！！原因:" + jsonObject.getString("message"));
            }
        }else {
            String value = commonInfoService.findOne(417).getValue();
            String url = "http://api.tianditu.gov.cn/geocoder";
            Map<String, String> param = new HashMap<>();
            JSONObject postStr = new JSONObject();
            postStr.put("lon", lng);
            postStr.put("lat", lat);
            postStr.put("ver", "1");
            param.put("postStr", postStr.toJSONString());
            param.put("type", "geocode");
            param.put("tk", value);
            String s = HttpClientUtil.doGet(url, param);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String status = jsonObject.getString("status");
            if ("0".equals(status)) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject addressComponent = result.getJSONObject("addressComponent");
                String city = addressComponent.getString("city");
                PageUtils pageUtils = new PageUtils(goodsShopDao.selectSearch(pages, impotr, lng, lat, city));
                return Result.success().put("data", pageUtils);
            }
        }
        return Result.error("获取定位失败！");
    }

    @Override
    public Result selectEvaluate(Integer page, Integer limit, Long shopId, String goodsId, Integer grade) {
        Page<Evaluate> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectEvaluate(pages, shopId, goodsId, grade));
        int goodReputation = goodsShopDao.selectGoodReputation(shopId, goodsId);
        int mediumReview = goodsShopDao.selectMediumReview(shopId, goodsId);
        int negativeComment = goodsShopDao.selectNegativeComment(shopId, goodsId);
        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("pageUtils", pageUtils);
        hashMap.put("goodReputation", goodReputation);
        hashMap.put("mediumReview", mediumReview);
        hashMap.put("negativeComment", negativeComment);
        return Result.success().put("data", hashMap);
    }

//    @Override
//    public Result selectEvaluateByGoodsId(Long goodsId, Integer page, Integer limit) {
//        Page<Evaluate> pages = new Page<>(page, limit);
//        String goodsIds = ","+String.valueOf(goodsId)+",";
//        PageUtils pageUtils = new PageUtils(goodsShopDao.selectEvaluateByGoodsId(pages, goodsIds));
//        return Result.success().put("data", pageUtils);
//    }

    @Override
    public Result selectGoodsById(Long goodsId) {
        Goods goods = goodsDao.selectGoodsById(goodsId);
        if (goods != null) {
            goods.setAttr(goodsAttrService.findByGoodsId(goodsId));
            goods.setSku(goodsSkuService.selectGoodsSkuByGoodsId(goodsId));
            return Result.success().put("data", goods);
        }
        return Result.success();
    }

    @Override
    public Result updateBatchStatus(String goodsIds, Integer status) {
        for (String goodsId : goodsIds.split(",")) {
            Goods goods = new Goods();
            goods.setStatus(status);
            goodsDao.update(goods, new QueryWrapper<Goods>().eq("goods_id", goodsId));
        }
        return Result.success();
    }

    @Override
    public Result deleteBatchIds(String goodsIds) {
        for (String goodsId : goodsIds.split(",")) {
            goodsDao.delete(new QueryWrapper<Goods>().eq("goods_id", goodsId));
            goodsAttrService.deleteGoodsAttr(Long.valueOf(goodsId));
        }
        return Result.success();


    }

    @Override
    public Result updateBatchInventory(String goodsIds, Integer inventory) {
        for (String goodsId : goodsIds.split(",")) {
            GoodsShopRelevancy goodsShopRelevancy = new GoodsShopRelevancy();
            goodsShopRelevancy.setInventory(inventory);
            goodsShopRelevancyDao.update(goodsShopRelevancy, new QueryWrapper<GoodsShopRelevancy>().eq("goods_id", goodsId));
        }
        return Result.success();
    }

    @Override
    public Result updateSort(Long goodsId, Integer sort) {
        Goods goods = new Goods();
        goods.setGoodsId(goodsId);
        goods.setSort(sort);
        goodsDao.updateById(goods);
        return Result.success();
    }

    @Override
    public Result selectEvaluateGoodsById(String goodsId, Integer grade, Integer page, Integer limit) {
        Page<Evaluate> pages = new Page<>(page, limit);
        PageUtils pageUtils = new PageUtils(goodsShopDao.selectEvaluateByGoodsId(pages, goodsId, grade));
        int goodReputation = goodsShopDao.selectGoodReputation(null, goodsId);
        int mediumReview = goodsShopDao.selectMediumReview(null, goodsId);
        int negativeComment = goodsShopDao.selectNegativeComment(null, goodsId);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("pageUtils", pageUtils);
        hashMap.put("goodReputation", goodReputation);
        hashMap.put("mediumReview", mediumReview);
        hashMap.put("negativeComment", negativeComment);
        return Result.success().put("data", hashMap);
    }

}
